package rs.arm.letthemusicplay.filechooser;

import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.text.DateFormat;

import rs.arm.letthemusicplay.MainActivity;
import rs.arm.letthemusicplay.PlaylistPicker;
import rs.arm.letthemusicplay.R;
import rs.arm.letthemusicplay.utilities.Constants;
import rs.arm.letthemusicplay.utilities.FileUtilities;
import android.os.Bundle;
import android.os.Environment;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;

public class FileChooser extends ListActivity {

	private File currentDir;
	private FileArrayAdapter adapter;
	private static final String FOLDER_MUSIC = Environment.getExternalStorageDirectory() + "/"
			+ Environment.DIRECTORY_MUSIC;
	private boolean addSong = false;
	private boolean isClicked = false;
	private String songForAdding = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		currentDir = new File(FOLDER_MUSIC);
		fill(currentDir);
		Intent i = getIntent();
		String startFrom = i.getStringExtra(Constants.INTENT_START_FROM);
		if (!TextUtils.isEmpty(startFrom)) {
			if (startFrom.equals(Constants.ACTIVITY_NAME_MAIN)) {
				addSong = true;
			} else {
				startFrom = null;
			}
		}
		if (TextUtils.isEmpty(startFrom) && FileUtilities.isAnyPlaylistInFolder()) {
			Dialog d = new PlaylistPicker(this);
			d.setTitle(getResources().getText(R.string.playlist_picker_title));
			d.show();
		}
	}

	private void fill(File f) {
		File[] dirs = f.listFiles();
		this.setTitle("Current Dir: " + f.getName());
		List<Item> dir = new ArrayList<Item>();
		List<Item> fls = new ArrayList<Item>();
		try {
			for (File ff : dirs) {
				Date lastModDate = new Date(ff.lastModified());
				DateFormat formater = DateFormat.getDateTimeInstance();
				String date_modify = formater.format(lastModDate);
				if (ff.isDirectory()) {

					File[] fbuf = ff.listFiles();
					int buf = 0;
					if (fbuf != null) {
						buf = fbuf.length;
					} else
						buf = 0;
					String num_item = String.valueOf(buf);
					if (buf == 0)
						num_item = num_item + " item";
					else
						num_item = num_item + " items";

					// String formated = lastModDate.toString();
					dir.add(new Item(ff.getName(), num_item, date_modify, ff.getAbsolutePath(),
							"snoopy_folder"));
				} else {
					if (isSupportedAudioFile(ff.getName())) {
						fls.add(new Item(ff.getName(), ff.length() + " Byte", date_modify, ff
								.getAbsolutePath(), "audio_file_icon"));
					}
				}
			}
		} catch (Exception e) {

		}
		Collections.sort(dir);
		Collections.sort(fls);
		dir.addAll(fls);
		if (!f.getPath().equals("/"))
			dir.add(0, new Item("..", "Parent Directory", "", f.getParent(), "directory_up"));
		adapter = new FileArrayAdapter(FileChooser.this, R.layout.custom_list_item, dir);
		this.setListAdapter(adapter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		Item o = adapter.getItem(position);
		if (o.getImage().equalsIgnoreCase("snoopy_folder")
				|| o.getImage().equalsIgnoreCase("directory_up")) {
			currentDir = new File(o.getPath());
			fill(currentDir);
		} else {
			onFileClick(o);
		}
	}

	private void onFileClick(Item o) {
		isClicked = true;
		if (addSong) {
			addSong = false;
			songForAdding = currentDir.toString() + "/" + o.getName();
			finish();
		} else {
			Intent intent = new Intent(this, MainActivity.class);
			intent.putExtra(Constants.INTENT_START_FROM, Constants.ACTIVITY_NAME_FILE_CHOOSER);
			intent.putExtra(Constants.INTENT_GET_PATH, currentDir.toString());
			intent.putExtra(Constants.INTENT_GET_FILE_NAME, o.getName());
			startActivity(intent);
			super.finish(); // for now
		}
	}

	@Override
	public void finish() {
		if (isClicked) {
			isClicked = false;
			Intent data = new Intent();
			data.putExtra(Constants.EXTRA_SONG_NAME, songForAdding);
			setResult(RESULT_OK, data);
		} else {
			setResult(RESULT_CANCELED);
		}
		super.finish();
	}

	private boolean isSupportedAudioFile(String path) {
		int lastIndex = path.lastIndexOf(".");
		if (lastIndex == -1)
			return true;
		String extension = path.substring(lastIndex + 1);
		if (extension.equalsIgnoreCase(Constants.FILE_EXTENSION_3GP)
				|| extension.equalsIgnoreCase(Constants.FILE_EXTENSION_MP3)
				|| extension.equalsIgnoreCase(Constants.FILE_EXTENSION_WAV)
				|| extension.equalsIgnoreCase(Constants.FILE_EXTENSION_OGG)
				|| extension.equalsIgnoreCase(Constants.FILE_EXTENSION_RAW))
			return true;
		return false;
	}

}
